package jvlite.dao.dataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import jvlite.core.JLiteContext;
import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBPool {

	protected static DataSource ds = null;

	// the static block would run only once
/*	static {
		// Initial the database pool
		try {
			InputStream in = JdbcSupport.class.getClassLoader()
					.getResourceAsStream("config.properties");
			Properties prop = new Properties();
			prop.load(in);
			ds = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}*/
	 

	static {
		try {
			Properties prop = new Properties();
			prop.setProperty("driverClassName", JLiteContext.driverClassName);
			prop.setProperty("url", JLiteContext.url);
			prop.setProperty("username", JLiteContext.username);
			prop.setProperty("password", JLiteContext.password);
			prop.setProperty("initialSize", JLiteContext.initialSize);
			prop.setProperty("maxActive", JLiteContext.maxActive);
			prop.setProperty("maxIdle", JLiteContext.maxIdle);
			prop.setProperty("minIdle", JLiteContext.minIdle);
			prop.setProperty("maxWait", JLiteContext.maxWait);
			prop.setProperty("connectionProperties",
					JLiteContext.connectionProperties);
			prop.setProperty("defaultAutoCommit", JLiteContext.defaultAutoCommit);
			prop.setProperty("defaultReadOnly", JLiteContext.defaultReadOnly);
			prop.setProperty("defaultTransactionIsolation",
					JLiteContext.defaultTransactionIsolation);
			ds = BasicDataSourceFactory.createDataSource(prop);
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() throws SQLException {
		// return the connection of database pool instead of real database
		// connection
		return ds.getConnection();
	}

	public static void release(Connection conn, Statement st, ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				// deal with the exception by log it on console
				e.printStackTrace();
			}
			// set result set as null to allow JVM recycle it
			rs = null;
		}
		if (st != null) {
			try {
				st.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			st = null;
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}